﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Ping9719.DeviceCommunication.Device
{
    /// <summary>
    /// 大族激光刻印
    /// </summary>
    public class DaZhuTcpMark : SocketBase
    {
        /// <summary>
        /// 使用Tcp的方式
        /// </summary>
        public DaZhuTcpMark(string ip, int port = 9001, int timeout = 60000)
        {
            if (socket == null)
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SetIpEndPoint(ip, port);
            this.timeout = timeout;
        }

        /// <summary>
        /// 加载指定模板
        /// </summary>
        /// <param name="name">模板名称</param>
        /// <param name="id">卡号</param>
        /// <param name="isClose">是否关闭在重新打开</param>
        /// <returns>可替换的文本数</returns>
        public Result<int> Initialize(string name, string id, bool isClose = false)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<int>(conn).EndTime();
            }

            string comm = $"<Initialize,{id},{(isClose ? 1 : 0)},{name}>";

            var result = new Result<int>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<int>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<int>(bbb).EndTime();

                result.Value = Convert.ToInt32(bbb.Value.FirstOrDefault());
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 卸载所有模板
        /// </summary>
        /// <returns></returns>
        public Result Uninstall()
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return conn.EndTime();
            }

            string comm = $"<Uninstall>";

            var result = new Result();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return aaa.EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return aaa.EndTime();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 得到所有卡号
        /// </summary>
        /// <returns>卡号</returns>
        public Result<string[]> GetCard()
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string[]>(conn).EndTime();
            }

            string comm = $"<GetCard>";

            var result = new Result<string[]>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<string[]>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<string[]>(bbb).EndTime();

                result.Value = bbb.Value;
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 替换打印模板
        /// </summary>
        /// <param name="id"></param>
        /// <param name="key">名称</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public Result Data(string key, string value, string id)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string[]>(conn).EndTime();
            }

            string comm = $"<Data,{id},{key},{value}>";
            var result = new Result<string[]>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<string[]>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<string[]>(bbb).EndTime();

                result.Value = bbb.Value;
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 开始打印
        /// </summary>
        /// <returns>打印时间（秒）</returns>
        public Result<double> MarkStart(params string[] id)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<double>(conn).EndTime();
            }

            string comm = $"<MarkStart,{string.Join(",", id)}>";
            var result = new Result<double>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<double>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<double>(bbb).EndTime();

                result.Value = Convert.ToDouble(bbb.Value.FirstOrDefault());
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 红光预览
        /// </summary>
        /// <returns>预览时间（秒）</returns>
        public Result<double> RedStart(params string[] id)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<double>(conn).EndTime();
            }

            string comm = $"<RedStart,{string.Join(",", id)}>";
            var result = new Result<double>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<double>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<double>(bbb).EndTime();

                result.Value = Convert.ToDouble(bbb.Value.FirstOrDefault());
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 停止指定设备刻印
        /// </summary>
        public Result Stop(params string[] id)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string[]>(conn).EndTime();
            }

            string comm = $"<Stop,{string.Join(",", id)}>";
            var result = new Result();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return aaa.EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return bbb.EndTime();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 停止所有设备刻印
        /// </summary>
        public Result StopAll()
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return conn.EndTime();
            }

            string comm = $"<Stop>";
            var result = new Result();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return aaa.EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return bbb.EndTime();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 查询指定设备状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns>值：Run/Ready</returns>
        public Result<string> State(string id)
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn).EndTime();
            }

            string comm = $"<State,{id}>";
            var result = new Result<string>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<string>(bbb).EndTime();

                result.Value = bbb.Value.FirstOrDefault();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 查询所有设备状态（只有一个在打标就是Run）
        /// </summary>
        /// <returns>值：Run/Ready</returns>
        public Result<string> State()
        {
            if (isAutoOpen)
            {
                var conn = Connect();
                if (!conn.IsSucceed)
                    return new Result<string>(conn).EndTime();
            }

            string comm = $"<State>";
            var result = new Result<string>();
            try
            {
                var aaa = SendPackageSingle(Encoding.UTF8.GetBytes(comm));
                if (!aaa.IsSucceed)
                    return new Result<string>(aaa).EndTime();

                var bbb = Analysis(Encoding.UTF8.GetString(aaa.Value));
                if (!bbb.IsSucceed)
                    return new Result<string>(bbb).EndTime();

                result.Value = bbb.Value.FirstOrDefault();
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Err = ex.Message;
            }
            finally
            {
                if (isAutoOpen)
                    Dispose();
            }
            return result.EndTime();
        }

        /// <summary>
        /// 解析返回结果
        /// </summary>
        /// <param name="str">返回的结果</param>
        /// <returns></returns>
        private Result<string[]> Analysis(string str)
        {
            Result<string[]> result = new Result<string[]>();
            if (str.StartsWith("<") && str.EndsWith(">"))
            {
                var con = str.Substring(1, str.Length - 2).Split(',');
                if (con.Length > 0 && con[0] == "OK")
                {
                    result.Value = con.Skip(1).ToArray();
                }
                else if (con.Length > 0 && con[0] == "NG")
                {
                    result.IsSucceed = false;
                    result.Err = string.Join(",", con.Skip(1));
                }
                else
                {
                    result.IsSucceed = false;
                    result.Err = $"不是有效的格式【{con}】";
                }
            }
            else
            {
                result.IsSucceed = false;
            }
            return result;
        }

    }
}
